package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) {
        if (StringUtils.isBlank(dto.getName())|| StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser wmUser = this.lambdaQuery().eq(WmUser::getName, dto.getName()).one();
        if (BeanUtil.isEmpty(wmUser)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        boolean checkpw = BCrypt.checkpw(dto.getPassword(), wmUser.getPassword());
        if (!checkpw) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        if (wmUser.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.INVALID_STATUS);
        }
        Map map = new HashMap();
        map.put("user",wmUser );
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}